<?php

namespace App\Http\Controllers\Refund;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\Chanjet\TplusCommonController;
use App\Http\Controllers\Order\SaleorderController;
use App\Http\Validate\Refund\CustomRefund;
use App\Models\Balance\Balance;
use App\Models\Custom\Custom;
use App\Models\Refund\CustomRefund as ModelCustomRefund;
use App\Models\Settle\SettleType;
use App\Services\Chanjet\ChanjetRequest;
use App\Services\Common\Common;
use Illuminate\Http\Request;
use App\Services\Common\SnCode;
use App\Models\Receivemoney\Receipt;
use Illuminate\Support\Facades\DB;
use App\Models\Settle\SettleCompany;
use Illuminate\Support\Facades\Log;

/**
 * 退款管理
 */
class CustomRefundController extends BaseController
{

    /**
     * 添加
     */
    public function dopostadd(Request $request)
    {
        $params = ['custom_id', 'custom_name', 'refund_type', 'pay_bank', 'contacts', 'bank_card_no', 'bank', 'bank_number', 'refund_amount', 'urgent_remark', 'contract_info', 'approve_id1', 'approve_id2', 'payment', 'business_license', 'account_opening_permit', 'attorney'];
        $req_data = $request->only($params);
        $validate = new CustomRefund('add');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }

        $mangerinfo = $this->mangerinfo;
        $cpid = $mangerinfo['cpid'] ?? 0;
        $manger_id = $mangerinfo['id'] ?? 0;

        $custom_id = $req_data['custom_id'];
        $refund_amount = $req_data['refund_amount'];

        $custom = Custom::where([
            'cpid' => $cpid,
            'id' => $custom_id
        ])->first();
        if (!$custom) {
            return response()->json(['code' => '001', 'msg' => '客户不存在']);
        }
        $custom = $custom->toArray();

        //余额是否充足
        $where = [
            'cpid' => $cpid,
            'custom_id' => $custom_id
        ];
        $balance = Balance::where($where)->first();
        if (!$balance) {
            return response()->json(['code' => '001', 'msg' => '客户不存在']);
        }
        $balance = $balance->balance;
        if ($balance < $refund_amount) {
            return response()->json(['code' => '001', 'msg' => '余额不足']);
        }

        $data = [
            'cpid' => $cpid,
            'manger_id' => $manger_id,
            'custom_name' => $req_data['custom_name'],
            'pay_at' => time(),
            'create_at' => time()
        ];
        //$req_data['bank'] = !empty($req_data['bank']) ? $req_data['bank']['bank'] : '';
        if(isset($req_data['bank']) && isset($req_data['bank']['bank'])){
            $req_data['bank'] = $req_data['bank']['bank'];
        }else{
            return response()->json(['code' => '001', 'msg' => '开户行不能为空']);
        }
        // $req_data['pay_bank'] = (int)$req_data['pay_bank'];
        // $req_data['banks'] = !empty($req_data['banks']) ? json_encode($req_data['banks']) : '';

        DB::beginTransaction();
        try {
//            Balance::where($where)
//                ->update([
//                    'balance' => DB::raw('balance - ' . $refund_amount),
//                    'update_at' => time()
//                ]);

            ModelCustomRefund::create($data + $req_data);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '退款添加失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 审核退款，通过、驳回
     */
    public function dopostedit(Request $request)
    {
        $params = ['id', 'audit_status'];
        $req_data = $request->only($params);
        $validate = new CustomRefund('dopostedit');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }

        $ids = $req_data['id'];
        foreach ($ids as $id) {
            $refund = ModelCustomRefund::where([
                'id' => $id
            ])->first();
            if (!$refund) {
                return response()->json(['code' => '001', 'msg' => '审核记录不存在']);
            }
            $refund = $refund->toArray();

            if ($refund['audit_status'] == $req_data['audit_status']) {
                return response()->json(['code' => '001', 'msg' => '不能重复审核']);
            }

            //审核通过数据
            $at = [];
            if ($req_data['audit_status'] == 2) {
                $at = [
                    'ts_at' => time(),
                ];
            } elseif ($req_data['audit_status'] == 3) {
                $at = [
                    'cp_at' => time(),
                ];
            }

            //审核驳回数据,写入驳回时间
            if($req_data['audit_status'] == 4){
                if(empty($refund['ts_at'])){
                    $at = [
                        'ts_at' => time(),
                    ];
                }
                if(!empty($refund['ts_at'])){
                    $at = [
                        'cp_at' => time(),
                    ];
                }
            }

            ModelCustomRefund::where([
                'id' => $id
            ])->update([
                'audit_status' => $req_data['audit_status'],
                'update_at' => time()
            ] + $at);
            //办款才加减 余额
//            if ($req_data['audit_status'] == 4) {
//                Balance::where([
//                    'custom_id' => $refund['custom_id']
//                ])->update([
//                    'balance' => DB::raw('balance + ' . $refund['refund_amount']),
//                    'update_at' => time()
//                ]);
//            }
        }
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    public function getlist(Request $request)
    {
        $memberinfo = $this->mangerinfo;
        $utype = $memberinfo['utype']??0;
        $isgetall = $request->isgetall ?? 0;
        $list = ModelCustomRefund::getList($request, $memberinfo, $isgetall);
        foreach ($list['list'] as $key => $value) {
            $list['list'][$key]['refund_amount'] = mathfuncmoney('div', $value['refund_amount'], 100, 2);
            $list['list'][$key]['bk_amount'] = mathfuncmoney('div', $value['bk_amount'], 100, 2);
            $list['list'][$key]['payment'] = json_decode($list['list'][$key]['payment'],true);
            /**
             *  1.销售才可以撤审
             *  2.状态为待审核和审核中的时候支持撤审，审核状态 1.待审核 2.统审审核 3.操盘审核 4.驳回。
             *
             */
            if($utype == '7' && in_array($value['audit_status'],['1','2'])){
                $list['list'][$key]['is_show_edit'] = true;
            }else{
                $list['list'][$key]['is_show_edit'] = false;
            }
        }
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }

    public function getlistone(Request $request)
    {
        $memberinfo = $this->mangerinfo;
        $isgetall = $request->isgetall ?? 0;
        $list = ModelCustomRefund::getListOne($request, $memberinfo, $isgetall);
        foreach ($list['list'] as $key => $value) {
            $list['list'][$key]['refund_amount'] = mathfuncmoney('div', $value['refund_amount'], 100, 2);
            $list['list'][$key]['bk_amount'] = mathfuncmoney('div', $value['bk_amount'], 100, 2);
        }
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }

    public function getlisttwo(Request $request)
    {
        $memberinfo = $this->mangerinfo;
        $utype = $memberinfo['utype']??0;
        $isgetall = $request->isgetall ?? 0;
        $list = ModelCustomRefund::getListTwo($request, $memberinfo, $isgetall);
        foreach ($list['list'] as $key => $value) {
            $list['list'][$key]['refund_amount'] = mathfuncmoney('div', $value['refund_amount'], 100, 2);
            $list['list'][$key]['bk_amount'] = mathfuncmoney('div', $value['bk_amount'], 100, 2);
            if(isset($list['list'][$key]['payment'])){
                $list['list'][$key]['payment'] = json_decode($list['list'][$key]['payment'],true);
            }
            /**
             *  1.销售才可以撤审
             *  2.状态为待审核和审核中的时候支持撤审，审核状态 1.待审核 2.统审审核 3.操盘审核 4.驳回。
             *
            */
            if($utype == '7' && in_array($value['audit_status'],['1','2'])){
                $list['list'][$key]['is_show_edit'] = true;
            }else{
                $list['list'][$key]['is_show_edit'] = false;
            }

        }
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }

    public function getone(Request $request)
    {
        $id = $request->id ?? 0;
        $one = ModelCustomRefund::with(['tsinfo', 'cpinfo', 'pminfo', 'paybank'])->where(['id' => $id])->first()->toArray();
        if (!$one) {
            return response()->json(['code' => '001', 'msg' => '订单不存在']);
        }
        $one['refund_amount'] = mathfuncmoney('div', $one['refund_amount'], 100, 2);
        $one['bk_amount'] = mathfuncmoney('div', $one['bk_amount'], 100, 2);

        $one['pay_mid'] = $one['manger_id'];
        $one['ts_mid'] = $one['approve_id1'];
        $one['cp_mid'] = $one['approve_id2'];

        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $one]);
    }

    /***
     *  退款-撤审
     *
     *  已经有办款记录的是否可以撤审？
     *
     *
    */
    public function review(Request $request)
    {
        $params = ['id'];
        $req_data = $request->only($params);
        $validate = new CustomRefund('review');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }

        $refund = ModelCustomRefund::where([
            'id' => $req_data['id']
        ])->first();
        if (!$refund) {
            return response()->json(['code' => '001', 'msg' => '审核记录不存在']);
        }
        $refund = $refund->toArray();

        if ($refund['audit_status'] > 3) {
            return response()->json(['code' => '001', 'msg' => '不允许撤审']);
        }

        DB::beginTransaction();
        try {
            /***
             *  审核通过后，出纳端办款，办完款后再释放
             *
            */
//            Balance::where([
//                'custom_id' => $refund['custom_id']
//            ])->update([
//                'balance' => DB::raw('balance + ' . $refund['refund_amount']),
//                'update_at' => time()
//            ]);

            ModelCustomRefund::where([
                'id' => $req_data['id']
            ])->update([
                //'audit_status' => 1,
                'audit_status' => 5,// 撤审后，状态改为5，2025.05.05
//                'approve_id1' => 0,
//                'approve_id2' => 0,
                'ts_at' => 0,
                'cp_at' => 0,
                'update_at' => time()
            ]);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '操作失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    public function getlistthree(Request $request)
    {
        $memberinfo = $this->mangerinfo;
        $isgetall = $request->isgetall ?? 0;
        $list = ModelCustomRefund::getListThree($request, $memberinfo, $isgetall);
        foreach ($list['list'] as $key => $value) {
            $list['list'][$key]['refund_amount'] = mathfuncmoney('div', $value['refund_amount'], 100, 2);
            $list['list'][$key]['bk_amount'] = mathfuncmoney('div', $value['bk_amount'], 100, 2);
            $list['list'][$key]['payment'] = json_decode($value['payment'],true);
        }
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }

    public function bankuan(Request $request)
    {
        $params = ['id', 'bank_name', 'bk_amount', 'bk_url', 'bk_remark'];
        $req_data = $request->only($params);
        $validate = new CustomRefund('bankuan');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }

        $refund = ModelCustomRefund::where([
            'id' => $req_data['id']
        ])->first();
        if (!$refund) {
            return response()->json(['code' => '001', 'msg' => '审核记录不存在']);
        }
        $refund = $refund->toArray();
        if(empty($req_data['bank_name'])){
            return response()->json(['code' => '001', 'msg' => '银行名称不能为空']);
        }
        if(!isset($req_data['bk_amount'])){
            return response()->json(['code' => '001', 'msg' => '办款金额异常']);
        }

        if(empty($req_data['bk_url'])){
            return response()->json(['code' => '001', 'msg' => '回单不能为空']);
        }


        $mangerinfo = $this->mangerinfo;
        $cpid = $mangerinfo['cpid'] ?? 0;
        $manger_id = $mangerinfo['id'] ?? 0;
        $realname = $mangerinfo['realname'];

        $custom = Custom::where('id', $refund['custom_id'])->first();
        if (!$custom) {
            return response()->json(['code' => '001', 'msg' => '客户信息异常']);
        }
        $custom = $custom->toArray();
        if (is_numeric($custom['settlement_company'])) {
            $settlement_company = SettleCompany::where([['id', (int)$custom['settlement_company']]])->first();
            if ($settlement_company) {
                $settlement_company = $settlement_company->toArray();
                $settlement_company_name = $settlement_company['settle_company_name'];
            } else {
                $settlement_company_name = '';
            }
        } else {
            $settlement_company_name = $custom['settlement_company'];
        }

        $sk_code = SnCode::getSnCode('TK_');
        $date = time();
        $data = [
            'cpid' => $cpid,
            'order_receiver_id' => $req_data['id'],
            'date' => $date,
            'code' => $sk_code,
            'category' => 2, //2销售退款
            'custom_name' => $realname . '-' . $custom['company_name'] . '*' . $settlement_company_name,
            'settlement_category' => 1, //1网银
            'settlement_company' => $settlement_company_name,
            'bank_name' => $req_data['bank_name'],
            'amount' => SaleorderController::amountTransformIntoCent($req_data['bk_amount']),
            'create_at' => $date,
            'manger_id' => $manger_id
        ];


        DB::beginTransaction();
        try{
            //退款列表
            ModelCustomRefund::where([
                'id' => $req_data['id']
            ])->update([
                'bk_status' => 2,
                //'bank_name' => $req_data['bank_name'],
                'bk_amount' => DB::raw('bk_amount + ' . SaleorderController::amountTransformIntoCent($req_data['bk_amount'])),
                //'bk_url' => $req_data['bk_url'],
                //'bk_remark' => $req_data['bk_remark'] ?? '',
            ]);
            //退款-办款详情
            \App\Models\Refund\CustomRefundBankuan::create([
                'cpid' => $cpid,
                'bank_name' => $req_data['bank_name'],
                'bk_amount' => SaleorderController::amountTransformIntoCent($req_data['bk_amount']),
                'bk_url'    => $req_data['bk_url'],
                'bk_remark' => $req_data['bk_remark'] ?? '',
                'main_id'   => $req_data['id'],
                'create_at' => time()
            ]);

            //负数收款单
            Receipt::create($data);

            //办款完成，扣除余额。
            Balance::where([
                'custom_id' => $refund['custom_id']
            ])->update([
                'balance' => DB::raw('balance - ' . SaleorderController::amountTransformIntoCent($req_data['bk_amount'])),
                'update_at' => time()
            ]);
            DB::commit();
        }catch(\Exception $e){
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '' . $e->getMessage()]);
        }







        /**
         *  T+退款, 负收款单
         *
         **/
        $Chanjet_param = [
            'type' => 'refund',
            'data' => $data,
            'custom' => $custom,
            'req_data' => $req_data
        ];
        $requestData = [
            "api" => "ReceivePaymentVoucherOpenApiNewCreate",
            "param" => $Chanjet_param,
            "mangerinfo" => $this->mangerinfo
        ];
        \App\Jobs\ReceiptPayment::dispatch($requestData);



//        if(TplusCommonController::isAllowRequestTplus($this->mangerinfo)) { //负数收款单
//            //创建账号和结算方式
//            $BankAccountCode = common::getPinyin($data["settlement_company"]).'_'.common::getPinyin($data['bank_name']);
//            $BankAccountName = $data["settlement_company"].'_'.$data['bank_name'];//结算公司+银行名称
//
//            TplusCommonController::createBankAccount($BankAccountCode,$BankAccountName,$this->mangerinfo["org_id"]);
//
//            $Chanjet_param = [
//                "dto" => [
//                    "VoucherDate" => date('Y-m-d',$date),
//                    "Code" => $sk_code,
//                    "IsModifiedCode" => "true",
//                    "ExternalCode" => $sk_code,
//                    "Partner" => [
//                        "Code" => $custom["id"],
//                        "Name" => $realname . '_' . $custom['company_name'] . '_' . $custom['settlement_company'],
//                    ],//往来单位编码
//                    "Department" => ["Code" => strval($this->mangerinfo["sys_dpm_id"])],//部门
//                    "IsReceiveFlag" => "true",//赋值为true，则为收款单;赋值为false，则为付款单
//                    "BusiType" => ["Code"=>"34"],//收款单时，包括33（普通收款），34（预收款）和45（直接收款）；
//                    "ArapMultiSettleDetails" => [ //多结算明细
//                        [
//                            "SettleStyle" => [SettleType::where('id', $data["settlement_category"])->value("type_no")], //网银code 认款单
//                            "BankAccount" => ["name" => $BankAccountName],
//                            "OrigAmount" => strval(-1 * abs($req_data['bk_amount']/100)),
//                        ]
//                    ]
//                ]
//            ];
//            ChanjetRequest::getInstance()->ReceivePaymentVoucherOpenApiNewCreate($Chanjet_param,$this->mangerinfo['org_id']);
//        }

        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    public function getlistfour(Request $request)
    {
        $memberinfo = $this->mangerinfo;
        $isgetall = $request->isgetall ?? 0;
        $list = ModelCustomRefund::getListFour($request, $memberinfo, $isgetall);
        foreach ($list['list'] as $key => $value) {
            $list['list'][$key]['refund_amount'] = mathfuncmoney('div', $value['refund_amount'], 100, 2);
            $list['list'][$key]['bk_amount'] = mathfuncmoney('div', $value['bk_amount'], 100, 2);
        }
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }
}
